const router = require('koa-router')()
const DB = require('../db')

/**
 * 获取某个用户的基础信息
 */
router.get('/myInfo', async (ctx, next) => {
  const userName = ctx.request.header.username;
  if (!userName) {
    ctx.body = {
      code: '0008',
      message: '没有登录信息',
      data: {}
    }
    return;
  }
  const r = await DB.find('users', { userName });
  if (!r || r.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未找到相关信息',
      data: {}
    }
    return;
  }
  const { nick, uid, avatarUrl, registerDate, sex } = r[0];
  ctx.body = {
    code: '0000',
    message: 'ok',
    data: { userName, nick, uid, avatarUrl, registerDate, sex }
  }
})

/**
 * 获取所有用户的信息
 */
router.get('/getAllUsersInfo', async (ctx, next) => {
  const r = await DB.find('users');
  if (!r || r.length === 0) {
    ctx.body = {
      code: '0013',
      message: '未找到相关信息',
      data: []
    }
    return;
  }
  const info = r.map((item) => {
    const { userName, nick, uid, avatarUrl, sex } = item;
    return {
      uname: userName,
      nick,
      uid,
      avatarUrl,
      sex
    }
  });
  ctx.body = {
    code: '0000',
    message: 'ok',
    data: info
  }
})

module.exports = router
